#include "imageviewtool.h"
#include "ui_imageviewtool.h"

#include <QGraphicsDropShadowEffect>

ImageViewTool::ImageViewTool(const QPixmap &pixmap, QDialog *parent) :
    QDialog(parent),
    ui(new Ui::ImageViewTool)
{
    ui->setupUi(this);

    this->setWindowFlags(this->windowFlags() | Qt::FramelessWindowHint
                         | Qt::WindowStaysOnTopHint | Qt::Dialog); // 设置无边框
    setWindowModality(Qt::ApplicationModal);
    setWindowState(windowState() | Qt::WindowFullScreen);

    // 设置窗口背景颜色
    this->setStyleSheet("background-color: #F5F5F5;");
    // 设置右侧控制栏背景颜色
    ui->widget_2->setStyleSheet("background-color: #FFFFFF; border-radius: 5px;");
    // 设置图片显示区域背景颜色
    ui->graphicsView->setStyleSheet("background-color: #E0E0E0; border-radius: 5px;");


    // 设置按钮样式
    setButtonStyle(ui->btnMagnify, QColor(33, 150, 243));   // 蓝色 - 放大
    setButtonStyle(ui->btnLessen, QColor(255, 152, 0));     // 橙色 - 缩小
    setButtonStyle(ui->btnBothTurn, QColor(156, 39, 176));  // 紫色 - 左右翻转
    setButtonStyle(ui->btnUpDownTurn, QColor(233, 30, 99)); // 粉色 - 上下翻转
    setButtonStyle(ui->btnRestart, QColor(96, 125, 139));   // 灰色 - 复位
    setButtonStyle(ui->btnClose, QColor(244, 67, 54));      // 红色 - 关闭

    // 设置悬停渐变效果
//    QString hoverGradientStyle = "QPushButton:hover { background: qlineargradient(x1:0, y1:0, x2:0, y2:1, stop:0 %1, stop:1 %2); }";
//    ui->btnMagnify->setStyleSheet(ui->btnMagnify->styleSheet() + hoverGradientStyle.arg("#64B5F6", "#2196F3"));
//    ui->btnLessen->setStyleSheet(ui->btnLessen->styleSheet() + hoverGradientStyle.arg("#FFB74D", "#FF9800"));
//    ui->btnBothTurn->setStyleSheet(ui->btnBothTurn->styleSheet() + hoverGradientStyle.arg("#CE93D8", "#9C27B0"));
//    ui->btnUpDownTurn->setStyleSheet(ui->btnUpDownTurn->styleSheet() + hoverGradientStyle.arg("#F48FB1", "#E91E63"));
//    ui->btnRestart->setStyleSheet(ui->btnRestart->styleSheet() + hoverGradientStyle.arg("#90A4AE", "#607D8B"));
//    ui->btnClose->setStyleSheet(ui->btnClose->styleSheet() + hoverGradientStyle.arg("#EF9A9A", "#F44336"));

    // 设置按钮工具提示
    ui->btnMagnify->setToolTip("放大图片");
    ui->btnLessen->setToolTip("缩小图片");
    ui->btnBothTurn->setToolTip("左右翻转图片");
    ui->btnUpDownTurn->setToolTip("上下翻转图片");
    ui->btnRestart->setToolTip("复位图片");
    ui->btnClose->setToolTip("关闭窗口");

    QImage sizedImg = QImage(pixmap.toImage());
    recvImgShowSignal(sizedImg);
}

ImageViewTool::~ImageViewTool()
{
    delete ui;
}


// 设置按钮样式的辅助函数
void ImageViewTool::setButtonStyle(QPushButton* btn, const QColor& baseColor) {
    // 设置按钮字体
    btn->setFont(QFont("微软雅黑", 12));

    // 设置按钮固定尺寸
    btn->setFixedSize(100, 40);

    // 设置按钮背景颜色和圆角
    QString style = QString(
        "QPushButton {"
        "    background-color: %1;" // 基础颜色
        "    color: white;"         // 文字颜色
        "    border: none;"         // 无边框
        "    border-radius: 5px;"   // 圆角
        "    padding: 10px 10px;"   // 内边距
        "}"
        "QPushButton:hover {"
        "    background-color: %2;" // 悬停时变亮
        "}"
        "QPushButton:pressed {"
        "    background-color: %3;" // 按下时变暗
        "    padding-top: 12px;"
        "    padding-left: 12px;"
        "}"
    ).arg(baseColor.name(), baseColor.lighter(115).name(), baseColor.darker(120).name());
    btn->setStyleSheet(style);

    // 添加阴影效果
    auto shadow = new QGraphicsDropShadowEffect(btn);
    shadow->setBlurRadius(10);
    shadow->setOffset(0, 4);
    shadow->setColor(QColor(0, 0, 0, 50));
    btn->setGraphicsEffect(shadow);
}


void ImageViewTool::recvImgShowSignal(QImage image)
{
    ui->graphicsView->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff);
    ui->graphicsView->setVerticalScrollBarPolicy(Qt::ScrollBarAlwaysOff);

    ui->graphicsView->setCursor(Qt::ArrowCursor); // 默认状态

    // 设置图片显示区域边框和阴影
    ui->graphicsView->setStyleSheet(
        "QGraphicsView {"
        "   border: 1px solid #CCCCCC;"
        "   border-radius: 5px;"
        "   background-color: #FFFFFF;"
        "}"
    );

    QPixmap ConvertPixmap = QPixmap::fromImage(image);//The QPixmap class is an off-screen image representation that can be used as a paint device
    m_graphicsScene = new QGraphicsScene(this);//要用QGraphicsView就必须要有QGraphicsScene搭配着用

    int nwith = ui->graphicsView->width();//获取界面控件Graphics View的宽度
    int nheight = ui->graphicsView->height();//获取界面控件Graphics View的高度

    nwith = ConvertPixmap.width();
    nheight = ConvertPixmap.height();

    // 获得屏幕大小
    QScreen *screen = QGuiApplication::primaryScreen();
    QRect screenGeometry = screen->geometry();
    nwith = screenGeometry.width() - 120;   // 减去的120是右边控制栏的
    nheight = screenGeometry.height();


    // 获取图片原始尺寸
    int imageWidth = ConvertPixmap.width();
    int imageHeight = ConvertPixmap.height();

    // 计算等比缩放的尺寸
    qreal scaleFactor = qMin(static_cast<qreal>(nwith) / imageWidth,
                             static_cast<qreal>(nheight) / imageHeight);
    int scaledWidth = static_cast<int>(imageWidth * scaleFactor);
    int scaledHeight = static_cast<int>(imageHeight * scaleFactor);

    // 创建缩放后的QPixmap对象
    QPixmap scaledPixmap = ConvertPixmap.scaled(scaledWidth, scaledHeight, Qt::KeepAspectRatio, Qt::SmoothTransformation);

    m_Image = new TImgWidget(&scaledPixmap);//实例化类TImgWidgett的对象m_Image，该类继承自QGraphicsItem，是自己写的类
    m_Image->setQGraphicsViewWH(nwith,nheight);//将界面控件Graphics View的width和height传进类m_Image中
//    m_Image->setMinScale(ConvertPixmap.width() > nwith ? nwith : ConvertPixmap.width(), // 设置图片最小缩小
//                         ConvertPixmap.height() > nheight ? nheight : ConvertPixmap.height());
    m_Image->setMinScale(ConvertPixmap.width() / 2, // 设置图片最小缩小
                         ConvertPixmap.height() / 2);
    m_graphicsScene->addItem(m_Image);//将QGraphicsItem类对象放进QGraphicsScene中
    ui->graphicsView->setSceneRect(QRectF(-(nwith/2),-(nheight/2),nwith,nheight));//使视窗的大小固定在原始大小，不会随图片的放大而放大（默认状态下图片放大的时候视窗两边会自动出现滚动条，并且视窗内的视野会变大），防止图片放大后重新缩小的时候视窗太大而不方便观察图片
    ui->graphicsView->setScene(m_graphicsScene);//Sets the current scene to scene. If scene is already being viewed, this function does nothing.
    ui->graphicsView->setFocus();//将界面的焦点设置到当前Graphics View控件

    m_Image->ResetItemPos();
}

void ImageViewTool::on_btnClose_clicked()
{
    this->close();
}

void ImageViewTool::on_btnRestart_clicked()
{
    QGraphicsItem *item = m_graphicsScene->items().first();
    item->setTransform(QTransform()); // 重置为原始状态

    m_Image->setFlippedY(false); // 重置垂直翻转状态
    m_Image->setFlippedX(false); // 重置水平翻转状态
    m_Image->ResetItemPos();
}

void ImageViewTool::on_btnUpDownTurn_clicked()
{
    QGraphicsItem *item = m_graphicsScene->items().first();
    QTransform transform = item->transform();

    // 检查当前是否已经垂直翻转
    if (transform.m22() < 0) {
        // 如果已经垂直翻转，则重置为原始状态
        transform.reset(); // 重置变换矩阵
        m_Image->setFlippedY(false); // 重置垂直翻转状态

        if (m_Image->getFlippedX()) {
            transform.scale(-1, 1); // 水平翻转
        }

    } else {
        // 如果没有垂直翻转，则应用垂直翻转
        transform.scale(1, -1); // 垂直翻转
        m_Image->setFlippedY(true); // 设置垂直翻转状态
    }

    item->setTransform(transform);
}

void ImageViewTool::on_btnBothTurn_clicked()
{
    QGraphicsItem *item = m_graphicsScene->items().first();
    QTransform transform = item->transform();

    // 检查当前是否已经水平翻转
    if (transform.m11() < 0) {
        // 如果已经水平翻转，则重置为原始状态
        transform.reset(); // 重置变换矩阵
        m_Image->setFlippedX(false); // 重置水平翻转状态

        if (m_Image->getFlippedY()) {
            transform.scale(1, -1); // 垂直翻转
        }

    } else {
        // 如果没有水平翻转，则应用水平翻转
        transform.scale(-1, 1); // 水平翻转
        m_Image->setFlippedX(true); // 设置水平翻转状态
    }

    item->setTransform(transform);
}

void ImageViewTool::on_btnMagnify_clicked()
{
    m_Image->setMax();
}

void ImageViewTool::on_btnLessen_clicked()
{
    m_Image->setMin();
}
